/** 
* Descripttion:  Copyright (c) 2020 Sprocomm. All rights reserved.
* version:  V1.0 
* Author:  Sprocomm
* Date: 2020-10-26 09:47:35
* LastEditors:  Sprocomm
* LastEditTime: 2020-10-26 09:49:07
**/
#include "imgtool.h"

int ImgOperate(int ActionFlag,int angle,int *CropCoorL,int *CropCoorR,char *OpenImage,char *NewIamge,double ZoomX,double ZoomY,double move_x,double move_y)
{	
	int nread = 0;
	FILE *NewFp;
	FILE *SrcFp = fopen( OpenImage, "rb" );
	if( NULL == SrcFp )
	{
		printf( "Bitmap file %s not found./n", OpenImage );
		return -1;
	}
	bmpfileheader Srcbfh;
	nread = fread( &Srcbfh, sizeof(Srcbfh), 1, SrcFp );

	if( Srcbfh.type != 0x4d42 )
	{
		printf( "File %s is not a bitmap file./n", OpenImage );
		return -2;
	}
	bmpinfoheader Srcbih;
	nread = fread( &Srcbih, sizeof(Srcbih), 1, SrcFp );

	nread = fseek( SrcFp, Srcbfh.offset, SEEK_SET );
	if( nread )	
	{
		printf( "Data Seek error./n" );
		return -3;
	}
	int Srcbytespl = ((Srcbih.width*Srcbih.bitcount+31)>>5)<<2;
	unsigned char* SrcImgdata = new unsigned char[Srcbytespl*Srcbih.height];
	nread = fread( SrcImgdata, Srcbytespl, Srcbih.height, SrcFp );
	fclose( SrcFp );

	TPicRegion Dst;
	TPicRegion Src;
	Src.byte_width=Srcbytespl;
	Src.height=Srcbih.height;
	Src.width=Srcbih.width;
	Src.pdata=SrcImgdata;
	long SrcMaxLen;
	if(ActionFlag==1)
	{	
		printf("going to rotate!/n");
		if(Srcbih.height>Srcbih.width)
			SrcMaxLen=Srcbih.height;
		else
			SrcMaxLen=Srcbih.width;
		Dst.height=long((double)SrcMaxLen*1.414+(double)0.999);
		Dst.byte_width=	((Dst.height*Srcbih.bitcount+31)>>5)<<2;
		unsigned char* DstImgdata = new unsigned char[Dst.byte_width*Dst.height];
		Dst.width = Dst.height;
		Dst.pdata=DstImgdata;
		PicRotary2(&Dst,&Src,angle,ZoomX,ZoomY,move_x,move_y);
		bmpfileheader Dstbfh;
		Dstbfh=Srcbfh;
		bmpinfoheader Dstbih;
		Dstbih=Srcbih;
		Dstbfh.size=Srcbfh.offset+Dst.byte_width*Dst.height;
		Dstbih.height=Dst.height;
		Dstbih.width=Dst.width;
		NewFp=fopen(NewIamge,"wb+");
		fwrite(&Dstbfh,sizeof(Dstbfh),1,NewFp);
		fclose(NewFp);
		NewFp=fopen(NewIamge,"ab");
		fwrite(&Dstbih,sizeof(Dstbih),1,NewFp);
		fwrite(Dst.pdata,sizeof(unsigned char),Dst.byte_width*Dst.height,NewFp);
		fclose(NewFp);
	}
	else if(ActionFlag==2)
	{
		printf("going to crop!/n");
		Dst.height=CropCoorR[1]-CropCoorL[1]+1;
		Dst.width =CropCoorR[0]-CropCoorL[0]+1;
		Dst.byte_width=	((Dst.width*Srcbih.bitcount+31)>>5)<<2;
		unsigned char* DstImgdata = new unsigned char[Dst.byte_width*Dst.height];
		Dst.pdata=DstImgdata;
		PicCrop(&Dst,&Src,CropCoorL,CropCoorR);
		bmpfileheader Dstbfh;
		Dstbfh=Srcbfh;
		bmpinfoheader Dstbih;
		Dstbih=Srcbih;
		Dstbfh.size=Srcbfh.offset+Dst.byte_width*Dst.height;
		Dstbih.height=Dst.height;
		Dstbih.width=Dst.width;
		NewFp=fopen(NewIamge,"wb+");
		fwrite(&Dstbfh,sizeof(Dstbfh),1,NewFp);
		fclose(NewFp);
		NewFp=fopen(NewIamge,"ab");
		fwrite(&Dstbih,sizeof(Dstbih),1,NewFp);
		fwrite(Dst.pdata,sizeof(unsigned char),Dst.byte_width*Dst.height,NewFp);
		fclose(NewFp);
	}
	return 0;
}